<template>
  <view class="realative body ">
    <view class="padding_top_30">
      <swiper style="height: 376rpx;" @change="changeswiper" :current="currentswiper">
        <swiper-item style="display: flex;justify-content: center;align-items: center;" v-for="(item,index) in cardList"
          :key="index" @touchstart="changes(item.cardNumber,item.orderNum,item.id)">
          <view class="realative">
            <image :src="item.productPictureUrl" class="card"></image>
            <view class="absolute_0 card">
              <view class="biaoqian"></view>
              <view class="biaoqian_two">
                <view>权益有效期：{{item.paymentTime.slice(0,10)}} 至 {{item.expiredTime.slice(0,10)}}</view>
                <view>卡号：{{item.cardNumber}}</view>
              </view>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>
    <view class="server-item-box margin_top_40">
      <view class="server-item-title">专享权益</view>
      <view>
        <view class="margin_bottom_20" style="position:relative" v-for="(item,index) in metaType2Items">
          <view class="server-item">
            <image :src="item.backgroundImgUrl" class="server-item"></image>
            <view style="position:absolute;top:0;left:0;">
              <view class="server-item-name">{{item.metaSimpleName}}</view>
              <view class="server-item-detail">
                <view class="server-item-center">
                  <view class="server-item-blue">{{(item.singleLimit/100)*item.num}}元</view>
                  <view class="server-item-gray">总金额</view>
                </view>
                <view class="line"></view>
                <view class="server-item-center">
                  <view class="server-item-blue">{{item.num-item.usedNum}}次</view>
                  <view class="server-item-gray">剩余次数</view>
                </view>
              </view>
              <view :class="currentDate<=expiredTime && item.num-item.usedNum > 0?'button':'button_gray'"
                @click="cometo(item.formType,item.formUrl,item.metaId)">去使用</view>

            </view>
          </view>
          <view class="detail">
            <view style="display:flex;" class="detail_buttton">
              <view style="flex:1;">权益使用详情</view>
              <view @click="zhankai(item)">{{item.isOpen?'收起更多':'展开更多'}}
                <image :src="item.isOpen?'../../static/home/up.png':'../../static/home/down.png'"
                  style="width: 40rpx;height: 40rpx;"></image>
              </view>
            </view>

          </view>
          <view class="line_two" v-if="item.isOpen"></view>
          <view class="detail_two" v-if="item.isOpen">
            <view style="display: flex;padding-left:25rpx;padding-right: 25rpx;padding-top:10rpx ;">
              <view style="flex:1;display: flex;">总金额:<view
                  style="font-size: 24rpx;font-weight: 500;letter-spacing: 1px;line-height: 17.38px;color: rgba(19, 136, 255, 100);">
                  {{(item.singleLimit/100)*item.num}}元
                </view>
              </view>
              <view style="display: flex;">单次金额:<view
                  style="font-size: 24rpx;font-weight: 500;letter-spacing: 1px;line-height: 17.38px;color: rgba(19, 136, 255, 100);">
                  {{item.singleLimit/100}}元
                </view>
              </view>
            </view>
            <view style="display: flex;padding-left:25rpx;padding-right: 25rpx;">
              <view style="display:flex ;">剩余次数:<view
                  style="font-size: 24rpx;font-weight: 500;letter-spacing: 1px;line-height: 17.38px;color: rgba(19, 136, 255, 100);">
                  {{item.num-item.usedNum}}次
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="margin_bottom_20" v-for="(item,index) in metaType3Items" :key="item.id">
          <view class="server-item-one" style="position:relative">
            <image :src="item.backgroundImgUrl" class="server-item-one"></image>
            <view style="position:absolute;top:30rpx;right:140rpx;"></view>
            <view style="position:absolute;top:0;left:0;">
              <view style="display:flex;align-items: center;">
                <view class="server-item-name_two">{{item.metaSimpleName}}</view>
                <view class="number">{{item.num===-1?'不限次数':`剩余${item.num-item.usedNum}次`}}</view>
              </view>
              <view class="server-item-name-description">{{item.remark}}</view>
             <view :class="(currentDate<=expiredTime && item.num===-1 && item.usedNum===0) || (item.num-item.usedNum > 0 && currentDate<=expiredTime && item.num!==-1 )?'button':'button_gray'"
                @click="cometo(item.formType,item.formUrl,item.metaId,item.num,item.usedNum)">去使用</view>

            </view>
          </view>
        </view>
        <!--        <view class="margin_bottom_20">
          <view class="server-item-one" style="position:relative">
            <image src="../../static/home/globa.png" class="server-item-one"></image>
            <view style="position:absolute;top:0;left:0;">
              <view style="display:flex;align-items: center;">
                <view class="server-item-name_two">全球找药协助</view>
                <view class="number">不限次数</view>
              </view>
              <view class="server-item-name-description">境内外特药最新资讯</view>
              <view class="button" @click="cometo(3)">去使用</view>
            </view>
          </view>
        </view> -->
      </view>
      <view style="height:50rpx"></view>
    </view>
    <view style="height:50rpx"></view>
  </view>

</template>
<script setup>
  import {
    onShow
  } from '@dcloudio/uni-app';
  import {
    onMounted,
    ref
  } from 'vue';
  import {
    getTokenkey,
    getMedicationCardList,
    getMetaList
  } from "../../request/order.js"
  import {
    fetchJunmpHete,
    activeJunmpHete
  } from "../../request/heye.js"
  import {
    formatMoney
  } from "../../utils/format";
  const currentswiper = ref(null)
  const cardList = ref([])
  const phone = ref(null)
  const open = ref(false)
  const currentCardNumber = ref(null)
  const currentOrderId = ref(null)
  const tokenKey = ref(null)
  const userAccounts = ref(null)
  const id = ref(null)
  const orderNum = ref(null)
  const cardNumber = ref(null)
  const metaType2Items = ref([])
  const metaType3Items = ref([])
  const paymentTime = ref(null)
  const expiredTime = ref(null)
  const currentDate = ref(null)
  onMounted(() => {
    currentDate.value = formatDate(new Date())
    uni.setStorageSync("index", 0)
    currentswiper.value=0
  })
  onShow(() => {
    currentswiper.value = uni.getStorageSync("index")
    phone.value = uni.getStorageSync("Phone")
    const cardListone = uni.getStorageSync("cardList") ?? []
    if (cardListone) {
      cardList.value = uni.getStorageSync("cardList")
    }
    const metaType2Itemsone = uni.getStorageSync("metaType2Items") ?? []
    if (metaType2Itemsone) {
      metaType2Items.value = uni.getStorageSync("metaType2Items")
    }
    const metaType3Itemsone = uni.getStorageSync("metaType3Items") ?? []
    if (metaType3Itemsone) {
      metaType3Items.value = uni.getStorageSync("metaType3Items")
    }
    getMedicationCardListDetail()
  })

  function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  function cometo(number, url, metaId,num,usedNum) {

    console.log(number, metaId)
    if (number === 9) {
      let params;
      params = {
        metaId: metaId,
        orderId: id.value,
        phone: phone.value
      }
      getTokenkey(params).then(res => {
        console.log("res",res)
        if (res.code === 200) {
          tokenKey.value = res.data.tokenKey
          userAccounts.value = res.data.userAccounts
          window.location = `${url}?userAccounts=${userAccounts.value}&tokenKey=${tokenKey.value}`
        } else {
          uni.showToast({
            title: res.message,
            icon: 'none'
          })
        }
      }).catch(err => {
        console.log(err)
        uni.showToast({
          title: err.message,
          icon: 'none'
        })
      })
    } else if (number === 2) {
      if (currentDate.value > expiredTime.value) {
        uni.showToast({
          title: "权益已过期",
          icon: 'none'
        })
        return
      }
      if (num-usedNum<=0) {
        uni.showToast({
          title: "次数已用尽",
          icon: 'none'
        })
        return
      }

      window.location = url


    } else if (number === 8) {
      if (currentDate.value > expiredTime.value) {
        uni.showToast({
          title: "权益已过期",
          icon: 'none'
        })
        return
      }
      window.location = url+`?orderId=${id.value}`
    } else if (number === 6) {
      getHeye(metaId, url)
    }
  }

  function getHeye(metaId, url) {
    fetchJunmpHete(metaId, id.value, 2).then(res => {
      // 跳转参数
      if (res.code === 200) {
        if (res.data.params) {
          window.location = `${url}?channelCode=${res.data.channelCode}&params=${res.data.params}`
        } else {
          activeHeye(res.data.channelCode, metaId, url)
        }
      } else {
        uni.showToast({
          title: res.message,
          icon: none
        })
      }
    }).catch(err => {
      uni.showToast({
        title: err.message,
        icon: none
      })
    })
  }


  function activeHeye(channelCode, metaId, url) {
    let data;
    data = {
      channelCode: channelCode,
      endTime: expiredTime.value,
      metaId: metaId,
      orderId: id.value,
      startTime: paymentTime.value,
      terminal: 2
    }
    activeJunmpHete(data, url).then(res => {
      if (res.code === 200) {
        window.location = `${url}?channelCode=${res.data.channelCode}&params=${res.data.params}`
      } else {
        uni.showToast({
          title: res.message,
          icon: none
        })
      }
    }).catch(err => {
      uni.showToast({
        title: err.message,
        icon: none
      })

    })
  }

  function zhankai(item) {
     item.isOpen = !item.isOpen;
  }

  function changeswiper(event) {
    // uni.setStorageSync("index",event.detail.current)
    currentswiper.value = event.detail.current
    uni.setStorageSync("index",currentswiper.value)
    console.log(cardList.value[event.detail.current].id)
    // console.log("event", )
    id.value = cardList.value[event.detail.current].id
    getMetaListDteail(cardList.value[event.detail.current].id)
    orderNum.value = cardList.value[event.detail.current].orderNums
    cardNumber.value = cardList.value[event.detail.current].cardNumbers
    expiredTime.value = cardList.value[event.detail.current].expiredTime
    paymentTime.value = cardList.value[event.detail.current].paymentTime

  }

  function changes(cardNumbers, orderNums) {
    // console.log("event", cardNumbers)

  }

  function getMedicationCardListDetail() {

        uni.showLoading({
          title: "加载中",
          mask: true,
          maskColor:"#9d9d9d"
        })
    getMedicationCardList().then(res => {
      uni.hideLoading()
      cardList.value = res.data.list ?? []
      if(cardList.value.length<=0){
        uni.navigateTo({
          url:"/pages/mine/activation"
        })
        return
      }
      uni.setStorageSync("cardList", cardList.value)
      console.log("res", cardList.value)
      if (cardList.value <= 0) {
        return
      }
      id.value = cardList.value[currentswiper.value].id
      orderNum.value = cardList.value[currentswiper.value].orderNums
      cardNumber.value = cardList.value[currentswiper.value].cardNumbers
      expiredTime.value = cardList.value[currentswiper.value].expiredTime
      paymentTime.value = cardList.value[currentswiper.value].paymentTime
      getMetaListDteail(cardList.value[currentswiper.value].id)
    }).catch(err => {
      uni.hideLoading()
      console.log("Err", err)
    })
  }
  function getMetaListDteail(orderId) {
    getMetaList(orderId).then(res => {

      console.log("item", res);
      // 假设响应的数据为一个数组
      // metaType2Items.value = res.data.filter(item => item.metaType === 2);
      metaType2Items.value = res.data?.filter(item => item.metaType === 2).map(item => {
          return {
            ...item, // 保留原有字段
            isOpen: false // 添加新字段，初始值为 false
          };
        });
      metaType3Items.value = res.data.filter(item => item.metaType === 3);
      console.log("MetaType 2 Items:", metaType2Items.value);
      console.log("MetaType 3 Items:", metaType3Items.value);
      uni.setStorageSync("metaType2Items", metaType2Items.value)
      uni.setStorageSync("metaType3Items", metaType3Items.value)
    }).catch(err => {
      console.error("Error occurred:", err);
    });
  }
</script>

<style>
  .line_two {
    width: 616rpx;
    height: 1rpx;
    background: rgba(219, 219, 219, 1);
    margin: 0 auto;

  }

  .detail_two {
    width: 660rpx;
    height: 90rpx;
    opacity: 1;
    border-bottom-left-radius: 10rpx;
    border-bottom-right-radius: 10rpx;
    background: rgba(245, 245, 245, 1);
    margin: 0 auto;
    font-size: 24rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    line-height: 34rpx;
    color: rgba(107, 107, 107, 1);
  }

  .detail_buttton {
    /* justify-content: center; */
    display: flex;
    align-items: center;
    font-size: 24rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    line-height: 34rpx;
    color: rgba(107, 107, 107, 1);
    padding: 25rpx;
  }

  .detail {
    width: 660rpx;
    height: 80rpx;
    opacity: 1;
    border-bottom-left-radius: 10rpx;
    border-bottom-right-radius: 10rpx;
    background: rgba(245, 245, 245, 1);
    margin: 0 auto;
  }

  .number {
    font-size: 28rpx;
    font-weight: 500;
    letter-spacing: 2px;
    line-height: 40rpx;
    color: rgba(19, 136, 255, 100);
    margin-top: 10rpx;
    margin-left: 10rpx;
  }

  .server-item-name-description {
    font-size: 24rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    line-height: 34rpx;
    color: rgba(89, 89, 89, 1);
    margin-left: 40rpx;
    margin-top: 20rpx;
    padding-bottom: 35rpx;
  }

  .margin_top_30 {
    margin-top: 30rpx;
  }

  .button {
    width: 194rpx;
    height: 60rpx;
    opacity: 1;
    border-radius: 100rpx;
    background: rgba(19, 136, 255, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 40rpx;
    margin-top: 25rpx;
    font-size: 32rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    line-height: 46rpx;
    color: rgba(255, 255, 255, 1);

  }

  .button_gray {
    width: 194rpx;
    height: 60rpx;
    opacity: 1;
    border-radius: 100rpx;
    background: rgba(189, 189, 189, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 40rpx;
    margin-top: 25rpx;
    font-size: 32rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    line-height: 46rpx;
    color: rgba(255, 255, 255, 1);

  }

  .line {
    height: 50rpx;
    width: 1rpx;
    background: rgba(0, 111, 255, 1);
    margin-left: 30rpx;
    margin-right: 30rpx;
    margin-top: 5rpx;
  }

  .server-item-center {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .server-item-gray {
    font-size: 24rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    line-height: 34rpx;
    color: rgba(120, 120, 120, 1);
  }

  .server-item-blue {
    font-size: 36rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    line-height: 52rpx;
    color: rgba(19, 136, 255, 100);
  }

  .server-item-detail {
    padding-left: 40rpx;
    padding-top: 10rpx;
    padding-right: 30rpx;
    display: flex;
  }

  .server-item-name {
    padding-left: 40rpx;
    padding-top: 30rpx;
    padding-right: 30rpx;
    font-size: 36rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    line-height: 52rpx;
    color: rgba(0, 0, 0, 1);

  }

  .server-item-name_two {
    font-size: 36rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    /* line-height: 52rpx; */
    color: rgba(0, 0, 0, 1);
    padding-left: 40rpx;
    height: 80rpx;
    max-width: 400rpx;
    display: flex;
    margin-top: 10rpx;
    align-items: center;
  }

  .margin_bottom_20 {
    margin-bottom: 30rpx;
  }

  .server-item-one {
    width: 660rpx;
    height: 284rpx;
    opacity: 1;
    border-radius: 10rpx;
    margin: 0 auto;
    background: rgba(237, 246, 255, 1);
  }

  .server-item {
    width: 660rpx;
    height: 284rpx;
    opacity: 1;
    border-top-right-radius: 10rpx;
    border-top-left-radius: 10rpx;
    margin: 0 auto;
    background: rgba(237, 246, 255, 1);
    position: relative;
  }

  .server-item-title {
    padding: 30rpx;
    font-size: 36rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    line-height: 52rpx;
    color: rgba(0, 0, 0, 1);
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .server-item-box {
    width: 700rpx;
    min-height: 1100rpx;
    opacity: 1;
    border-radius: 10px;
    background: rgba(255, 255, 255, 1);
    margin: 0 auto;
  }

  .body {
    background: linear-gradient(180deg, rgba(209, 232, 255, 1) 0%, rgba(237, 246, 255, 1) 100%);
    min-height: 89vh
  }

  .padding_30 {
    padding: 30rpx;
  }

  .padding_top_30 {
    padding-top: 30rpx;
  }

  .margin_top_40 {
    margin-top: 40rpx
  }

  .biaoqian_two {
    height: 190rpx;
    display: flex;
    justify-content: center;
    /* align-items: center; */
    flex-direction: column;
    padding-left: 70rpx;
    font-size: 28rpx;
    font-weight: 500;
    letter-spacing: 0px;
    line-height: 40rpx;
    color: rgba(255, 255, 255, 1);
  }

  .biaoqian {
    height: 185rpx;
    display: flex;
    /* justify-content: center; */
    font-size: 36rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    line-height: 52rpx;
    color: rgba(255, 255, 255, 1);
    align-items: center;
    padding-left: 250rpx;

  }

  .absolute_0 {
    position: absolute;
    top: 0;
    left: 0;
  }

  .realative {
    position: relative;
  }

  .card {
    width: 700rpx;
    height: 376rpx;
    opacity: 1;
    border-radius: 40rpx;
  }
</style>
